package com.example.remotecontrol.ui.remote

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.FastForward
import androidx.compose.material.icons.filled.FastRewind
import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.material.icons.filled.Input
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Power
import androidx.compose.material.icons.filled.Radio
import androidx.compose.material.icons.filled.Repeat
import androidx.compose.material.icons.filled.Shuffle
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.Usb
import androidx.compose.material.icons.filled.VolumeDown
import androidx.compose.material.icons.filled.VolumeMute
import androidx.compose.material.icons.filled.VolumeUp
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel

/**
 * 音响遥控器界面
 */
@Composable
fun AudioRemoteScreen(
    viewModel: RemoteViewModel = hiltViewModel()
) {
    val selectedDevice by viewModel.selectedDevice.collectAsState()
    val irAvailable by viewModel.irAvailable.collectAsState()
    
    // 音响状态
    var isPoweredOn by remember { mutableStateOf(false) }
    var isPlaying by remember { mutableStateOf(false) }
    var volume by remember { mutableFloatStateOf(0.5f) }
    var isMuted by remember { mutableStateOf(false) }
    var currentInput by remember { mutableStateOf(AudioInput.BLUETOOTH) }
    var isRepeatOn by remember { mutableStateOf(false) }
    var isShuffleOn by remember { mutableStateOf(false) }
    
    Surface(
        modifier = Modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 设备名称
            Text(
                text = selectedDevice?.name ?: "音响遥控器",
                style = MaterialTheme.typography.titleLarge,
                textAlign = TextAlign.Center
            )
            
            if (!irAvailable) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "您的设备不支持红外功能",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center
                )
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 电源按钮
            AudioButton(
                icon = Icons.Default.Power,
                text = if (isPoweredOn) "关闭" else "打开",
                color = if (isPoweredOn) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary,
                size = 64.dp,
                onClick = {
                    isPoweredOn = !isPoweredOn
                    viewModel.sendIRCommand("POWER")
                },
                enabled = irAvailable
            )
            
            Spacer(modifier = Modifier.height(32.dp))
            
            // 如果电源关闭，不显示其他控制
            if (isPoweredOn) {
                // 音量控制
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "音量控制",
                            style = MaterialTheme.typography.titleMedium
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            // 音量减按钮
                            AudioButton(
                                icon = Icons.Default.VolumeDown,
                                size = 48.dp,
                                onClick = {
                                    if (volume > 0.0f) {
                                        volume -= 0.05f
                                        viewModel.sendIRCommand("VOLUME_DOWN")
                                    }
                                },
                                enabled = irAvailable && !isMuted
                            )
                            
                            // 音量滑块
                            Slider(
                                value = if (isMuted) 0f else volume,
                                onValueChange = { 
                                    volume = it 
                                    if (isMuted && it > 0) {
                                        isMuted = false
                                        viewModel.sendIRCommand("MUTE")
                                    }
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .padding(horizontal = 8.dp),
                                enabled = irAvailable
                            )
                            
                            // 音量加按钮
                            AudioButton(
                                icon = Icons.Default.VolumeUp,
                                size = 48.dp,
                                onClick = {
                                    if (volume < 1.0f) {
                                        volume += 0.05f
                                        viewModel.sendIRCommand("VOLUME_UP")
                                    }
                                },
                                enabled = irAvailable && !isMuted
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        // 静音按钮
                        AudioButton(
                            icon = if (isMuted) Icons.Default.VolumeMute else Icons.Default.VolumeMute,
                            text = if (isMuted) "取消静音" else "静音",
                            color = if (isMuted) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary,
                            onClick = {
                                isMuted = !isMuted
                                viewModel.sendIRCommand("MUTE")
                            },
                            enabled = irAvailable
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(24.dp))
                
                // 播放控制
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "播放控制",
                            style = MaterialTheme.typography.titleMedium
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            // 上一首
                            AudioButton(
                                icon = Icons.Default.SkipPrevious,
                                size = 56.dp,
                                onClick = {
                                    viewModel.sendIRCommand("PREV")
                                },
                                enabled = irAvailable
                            )
                            
                            // 快退
                            AudioButton(
                                icon = Icons.Default.FastRewind,
                                size = 56.dp,
                                onClick = {
                                    viewModel.sendIRCommand("REWIND")
                                },
                                enabled = irAvailable
                            )
                            
                            // 播放/暂停
                            AudioButton(
                                icon = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow,
                                size = 64.dp,
                                onClick = {
                                    isPlaying = !isPlaying
                                    viewModel.sendIRCommand(if (isPlaying) "PLAY" else "PAUSE")
                                },
                                color = if (isPlaying) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary,
                                enabled = irAvailable
                            )
                            
                            // 快进
                            AudioButton(
                                icon = Icons.Default.FastForward,
                                size = 56.dp,
                                onClick = {
                                    viewModel.sendIRCommand("FORWARD")
                                },
                                enabled = irAvailable
                            )
                            
                            // 下一首
                            AudioButton(
                                icon = Icons.Default.SkipNext,
                                size = 56.dp,
                                onClick = {
                                    viewModel.sendIRCommand("NEXT")
                                },
                                enabled = irAvailable
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            // 停止
                            AudioButton(
                                icon = Icons.Default.Stop,
                                text = "停止",
                                onClick = {
                                    isPlaying = false
                                    viewModel.sendIRCommand("STOP")
                                },
                                enabled = irAvailable
                            )
                            
                            // 重复
                            AudioButton(
                                icon = Icons.Default.Repeat,
                                text = "重复",
                                onClick = {
                                    isRepeatOn = !isRepeatOn
                                    viewModel.sendIRCommand("REPEAT")
                                },
                                color = if (isRepeatOn) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary,
                                enabled = irAvailable
                            )
                            
                            // 随机播放
                            AudioButton(
                                icon = Icons.Default.Shuffle,
                                text = "随机",
                                onClick = {
                                    isShuffleOn = !isShuffleOn
                                    viewModel.sendIRCommand("SHUFFLE")
                                },
                                color = if (isShuffleOn) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary,
                                enabled = irAvailable
                            )
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(24.dp))
                
                // 输入源选择
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "输入源",
                            style = MaterialTheme.typography.titleMedium
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            InputSourceButton(
                                icon = Icons.Default.Bluetooth,
                                label = "蓝牙",
                                isSelected = currentInput == AudioInput.BLUETOOTH,
                                onClick = {
                                    currentInput = AudioInput.BLUETOOTH
                                    viewModel.sendIRCommand("BLUETOOTH")
                                },
                                enabled = irAvailable
                            )
                            
                            InputSourceButton(
                                icon = Icons.Default.Usb,
                                label = "USB",
                                isSelected = currentInput == AudioInput.USB,
                                onClick = {
                                    currentInput = AudioInput.USB
                                    viewModel.sendIRCommand("USB")
                                },
                                enabled = irAvailable
                            )
                            
                            InputSourceButton(
                                icon = Icons.Default.Input,
                                label = "AUX",
                                isSelected = currentInput == AudioInput.AUX,
                                onClick = {
                                    currentInput = AudioInput.AUX
                                    viewModel.sendIRCommand("AUX")
                                },
                                enabled = irAvailable
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            InputSourceButton(
                                icon = Icons.Default.Radio,
                                label = "FM",
                                isSelected = currentInput == AudioInput.FM,
                                onClick = {
                                    currentInput = AudioInput.FM
                                    viewModel.sendIRCommand("FM")
                                },
                                enabled = irAvailable
                            )
                            
                            InputSourceButton(
                                icon = Icons.Default.GraphicEq,
                                label = "光纤",
                                isSelected = currentInput == AudioInput.OPTICAL,
                                onClick = {
                                    currentInput = AudioInput.OPTICAL
                                    viewModel.sendIRCommand("OPTICAL")
                                },
                                enabled = irAvailable
                            )
                            
                            InputSourceButton(
                                icon = Icons.Default.Input,
                                label = "HDMI",
                                isSelected = currentInput == AudioInput.HDMI,
                                onClick = {
                                    currentInput = AudioInput.HDMI
                                    viewModel.sendIRCommand("HDMI")
                                },
                                enabled = irAvailable
                            )
                        }
                    }
                }
            }
        }
    }
}

/**
 * 音响按钮
 */
@Composable
fun AudioButton(
    icon: ImageVector,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    text: String? = null,
    size: Double = 40.0,
    color: Color = MaterialTheme.colorScheme.primary,
    enabled: Boolean = true
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            modifier = modifier
                .size(size.dp)
                .clip(CircleShape)
                .background(if (enabled) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.surfaceVariant)
                .border(
                    width = 1.dp,
                    color = if (enabled) color else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f),
                    shape = CircleShape
                )
                .clickable(enabled = enabled, onClick = onClick),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = text,
                tint = if (enabled) color else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
            )
        }
        
        if (text != null) {
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = text,
                style = MaterialTheme.typography.bodySmall,
                color = if (enabled) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
            )
        }
    }
}

/**
 * 输入源按钮
 */
@Composable
fun InputSourceButton(
    icon: ImageVector,
    label: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    enabled: Boolean = true
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .clip(RoundedCornerShape(8.dp))
            .clickable(enabled = enabled, onClick = onClick)
            .padding(8.dp)
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(
                    if (isSelected) MaterialTheme.colorScheme.primaryContainer
                    else MaterialTheme.colorScheme.surfaceVariant
                ),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = label,
                tint = if (isSelected) MaterialTheme.colorScheme.primary
                      else if (enabled) MaterialTheme.colorScheme.onSurfaceVariant
                      else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.38f),
                modifier = Modifier.size(24.dp)
            )
        }
        
        Spacer(modifier = Modifier.height(4.dp))
        
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = if (isSelected) MaterialTheme.colorScheme.primary
                   else if (enabled) MaterialTheme.colorScheme.onSurface
                   else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
        )
    }
}

/**
 * 音频输入源
 */
enum class AudioInput {
    BLUETOOTH, USB, AUX, FM, OPTICAL, HDMI
} 